const db = wx.cloud.database()
const musiclist = db.collection('musiclist')  //获取音乐集合
const audioCtx = wx.createInnerAudioContext()
Page({
  data:{
    tab:0,
    item:0,
    state:'paused'
  },
  onLoad(){
    musiclist.get().then(res=>{
      let arr=[...res.data]
      for(let i=0;i<arr.length;i++){
        let random = parseInt(Math.random()*(arr.length-1));
        let current = arr[i]
        arr[i] = arr[random]
        arr[random] = current;
      }
      this.setData({
        musiclist:arr,musiclistt:arr
      })
      this.selectMusic(0)
    })

    audioCtx.onError(err=>{
      console.log('播放失败',err.audioCtx.src)
    })

    audioCtx.onCanplay(()=>{
      this.setData({
        'play.duration':audioCtx.duration
      })
      if(this.data.state == 'running'){
        audioCtx.play()
      }
    })

    audioCtx.onTimeUpdate(()=>{
      this.setData({
        'play.duration':audioCtx.duration,
        'play.currentTime':audioCtx.currentTime,
        'play.percent':audioCtx.currentTime / audioCtx.duration * 100
      })
    })

  },
  changeItem(e){
    console.log(e)
    this.setData({
      item:e.currentTarget.dataset.item
    })
  },
  changeTab(e){
    console.log(e)
    this.setData({
      tab:e.detail.current
    })
  },
  selectMusic(index){
        let music = this.data.musiclistt[index]
        audioCtx.src = music.src
        this.setData({
          playIndex:index,
          play:music,
          'play.currentTime':0,
          'play.duration':0,
          'play.percent':0
        })
  },
  play(){
    audioCtx.play()
    this.setData({
      state:'running'
    })
  },
  pause(){
    audioCtx.pause()
    this.setData({
      state:'paused'
    })
  },
  next(){
    let  index = this.data.playIndex >= this.data.musiclistt.length -1 ? 0 : this.data.playIndex+1
    this.selectMusic(index)
    if(this.data.state == 'running'){
      this.play()
    }
  },
change(e){
  console.log(e)
  this.selectMusic(e.currentTarget.dataset.index)
  this.play()
},
sliderchange(e){  //实现拖动进度条的功能
  audioCtx.seek(e.detail.value / 100 * this.data.play.duration)
},
aiyo(e){
  this.selectMusic(e.currentTarget.dataset.index)
  this.play()
  // console.log(e)
  // let title = e.currentTarget.dataset.name
  // let musiclist = this.data.musiclist
  // console.log(title)
  // let x = musiclist.find((x)=>{
  //    return x['title'] == title
  // })
  //      console.log(x)
  //      this.play()
}
})